import { Controller, Get, Query, BadRequestException } from '@nestjs/common';
import { AppService } from './app.service';
import { randomUUID } from "crypto";
import * as qrcode from "qrcode";


// 正常情况下，二维码生成后，需要在redis中保存一份，这里我们简化一下，直接用map存一下
interface QrCodeInfo {
  status: "noscan" | "scan-await-confirm" | "scan-confirm" | "scan-cancel" | "expired",
  userInfo?: {
    userId: number
  }
}
const map = new Map<string, QrCodeInfo>();

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) { }

  // 验证服务是否启动接口
  @Get()
  getHello(): string {
    return this.appService.getHello();
  }

  @Get("qrcode/generate")
  async generate() {
    const uuid = randomUUID();
    // 重定向到一个包含二维码图片的html页面，二维码图片包含的的内容应该：如果是app扫码就是确认登录的页面，如果是手机浏览器扫码，应该是下载app页面
    // const dataUrl = await qrcode.toDataURL(uuid); 验证二维码是否可以正常生成
    const dataUrl = await qrcode.toDataURL(`http://192.168.244.137:3000/pages/confirm.html?id=${uuid}`);
    // 往redis中存一份，这里使用map替代
    map.set(`qrcode_${uuid}`, {
      status: "noscan"
    });
    return {
      qrcode_id: uuid,
      img: dataUrl
    }
  }

  @Get("qrcode/check")
  async check(@Query("id") id: string) {
    return map.get(`qrcode_${id}`);
  }

  @Get("qrcode/scan")
  async scan(@Query('id') id: string) {
    const info = map.get(`qrcode_${id}`);
    if (!info) throw new BadRequestException("二维码已过期");
    info.status = "scan-await-confirm";
    return "success";
  }

  @Get("qrcode/confirm")
  async confirm(@Query('id') id: string) {
    const info = map.get(`qrcode_${id}`);
    if (!info) throw new BadRequestException("二维码已过期");
    info.status = "scan-confirm";
    return "success";
  }

  @Get("qrcode/cancel")
  async cancel(@Query('id') id: string) {
    const info = map.get(`qrcode_${id}`);
    if (!info) throw new BadRequestException("二维码已过期");
    info.status = "scan-cancel";
    return "success";
  }
}
